package com.next.aap.server.tasks;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.next.aap.client.UserDeviceWeb;
import com.next.aap.server.controller.MessageSender;
import com.next.aap.server.services.AppService;

@Component
@Scope(value = "prototype")
public class SendMessageTask implements Runnable {

	@Autowired
	private AppService appService;
	@Autowired
	private MessageSender messageSender;
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private String messageType;
	private Object message;
	public void run() {
		try{
			long startId = 0;
			int pageSize = 100;
			List<UserDeviceWeb> userDevices;
			List<String> deviceList = new ArrayList<String>();
			int batchNumber = 1;
			while(true){
				//get a batch of Android devices
				userDevices = appService.getAndroidUserDevices(startId, pageSize);
				if(userDevices.isEmpty()){
					break;
				}
				deviceList.clear();
				for(UserDeviceWeb oneUserDeviceWeb:userDevices){
					logger.info("oneUserDeviceWeb.getRegId() = "+oneUserDeviceWeb.getRegId());
					deviceList.add(oneUserDeviceWeb.getRegId());
					startId = oneUserDeviceWeb.getId();
				}
				logger.info("sending mesage to batch "+batchNumber);
				messageSender.sendMessage(message, messageType, deviceList);
				batchNumber++;
			}
		}catch(Exception ex){
			logger.error("Unable to send Notifications",ex);
		}
		
	}
	
	public String getMessageType() {
		return messageType;
	}
	public void setMessageType(String messageType) {
		this.messageType = messageType;
	}
	public Object getMessage() {
		return message;
	}
	public void setMessage(Object message) {
		this.message = message;
	}

}
